package com.yict.csms.interceptors;

import java.io.Serializable;
import java.util.Date;

import org.apache.commons.beanutils.PropertyUtils;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.TimestampType;
import org.hibernate.type.Type;
import org.springframework.stereotype.Component;

@Component("operateDateInterceptor")
public class OperateDateInterceptor extends EmptyInterceptor implements
		Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public boolean onFlushDirty(Object entity, Serializable id,
			Object[] currentState, Object[] previousState,
			String[] propertyNames, Type[] types) {
		if(previousState == null || previousState.length == 0) 
			return false;
		for(int i = 0;i < propertyNames.length;i++){
			if(types[i] instanceof TimestampType && "updatedate".equalsIgnoreCase(propertyNames[i])){
				/*Date preDate = (Date)previousState[i];
				Date curDate = (Date)currentState[i];
				if(preDate != null && curDate != null && curDate.compareTo(preDate) < 0){
					throw new RuntimeException("数据过期");
				}*/
				
				currentState[i] = new Date();
				break;
			}
		}
		
		return false;
	};

	@Override
	public boolean onSave(Object entity, Serializable id, Object[] state,
			String[] propertyNames, Type[] types) {
		Date newDate = new Date();
		for(int i = 0;i < propertyNames.length;i++){
			if(types[i] instanceof TimestampType && "createdate".equalsIgnoreCase(propertyNames[i])){
				//state[i] = newDate;
				try {
//					PropertyUtils.setProperty(entity, propertyNames[i], newDate);
					state[i] = newDate;
				}catch (Exception e) {
					e.printStackTrace();
				}
				break;
			}
		}
		/*for(int i = 0;i < propertyNames.length;i++){
			if(types[i] instanceof TimestampType && "updatedate".equalsIgnoreCase(propertyNames[i])){
				state[i] = newDate;
				break;
			}
		}*/
		return false;
	}
}
